#include "stdafx.h"
#include "VImageViewerMainWidow.h"
#include "loadFile.h"
#include "downloadFiles.h"

QString getVrefFileFromURL (QUrl url) {	
	QString fileName(QCoreApplication::applicationDirPath() + QString("\\xray.href"));		
	QFile file(fileName);
	file.open(QIODevice::WriteOnly | QIODevice::Text);
	QTextStream out(&file);	
	out << url.toString();
	file.close();
	return fileName;
}


void VImageViewerMainWindow::setupChildProcess(){
	QMessageBox::information(this, tr("Child Procc"), 
                        tr("Child Procc"));
}

VImageViewerMainWindow::VImageViewerMainWindow(QWidget * parent, Qt::WFlags flags)
	: QMainWindow(parent, flags)
	,firstLoading(true)
	,imageViewer(NULL)
	,isWidgetShown(false)
	,label(NULL)
{	
	imageViewer = new VImageViewerWidget;	
	imageViewer->mainWindowParent = this;
	setFocusProxy(imageViewer);
	setCentralWidget(imageViewer);
	//QMessageBox::warning(this, "WM_COPYDATA message", "widget created");		
	QWidget *widget = new QWidget();	
	setWindowTitle("Vidar-XRAY");	
	QDir::setCurrent(QCoreApplication::applicationDirPath());
	if(Panel::mEMManager == NULL){
		Panel::mEMManager = new MEMManager();
		Panel::mEMManager->start();
	}
	curFilter = new QString("");
	char buff[256];	
	char * MyString = new char[10];	
	QString Path = getWindowAppPath();	
	QString FileName = Path + QString("\\settings.ini");		 
	HANDLE file = CreateFile(FileName.toAscii().constData(), GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	int result = GetFileSize (file, NULL);	
	CloseHandle(file);	
	if(!QFile::exists(FileName)){
		QFile file(filePath);
		file.open(QIODevice::ReadOnly);
		file.close();
	}
	char * store = new char[1000];
	GetPrivateProfileString ("style",  "bgMenuBar", "AAAAFF", store, 100 , FileName.toAscii().constData());	
	WritePrivateProfileStringA("style", "bgMenuBar", store, FileName.toAscii().constData());
	//store = "green;"; 
	QString styles(
		"QMenuBar{"
		//"font: bold 15px;"	
		"background-color: #");
	styles.append(store);
	delete store;
	styles.append(
		";}"
	"QToolBar"	
	"{"		
		"background-color: #"
	);
	store = new char[100];
	GetPrivateProfileString ("style",  "bgToolBarColor", "AAAAFF", store, 100 , FileName.toAscii().constData());	
	WritePrivateProfileString("style", "bgToolBarColor", store, FileName.toAscii().constData());
	styles.append(store);
	delete store;
	styles.append(
	";"	
     "}"  	
	"QToolButton{"
		"background-color: #"
	);
	store = new char[100];
	GetPrivateProfileString ("style",  "bgToolBarButtonColor", "00FF00", store, 100 , FileName.toAscii().constData());	
	WritePrivateProfileString("style", "bgToolBarButtonColor", store, FileName.toAscii().constData());
	styles.append(store);
	delete store;	
	styles.append(
		 ";"	
	"padding: ");
	store = new char[100];
	GetPrivateProfileString ("style",  "ToolBarButtonPadding", "5", store, 100 , FileName.toAscii().constData());	
	WritePrivateProfileString("style", "ToolBarButtonPadding", store, FileName.toAscii().constData());
	styles.append(store);
	delete store;
	styles.append(
			"px;"
			"border-style: outset;"
	 "border-color: #");
	store = new char[100];
	GetPrivateProfileString ("style",  "ToolBarButtonBorderColor", "FF00FF", store, 100 , FileName.toAscii().constData());	
	WritePrivateProfileString("style", "ToolBarButtonBorderColor", store, FileName.toAscii().constData());
	styles.append(store);
	delete store;
	styles.append(
		";"
	 "border-width: ");
	store = new char[100];
	GetPrivateProfileString ("style",  "ToolBarButtonBorderWidth", "2", store, 100 , FileName.toAscii().constData());	
	WritePrivateProfileString("style", "ToolBarButtonBorderWidth", store, FileName.toAscii().constData());
	styles.append(store);
	delete store;
	styles.append(
		"px;"
	"}"
	  "QToolButton:checked {"		
		"background: #");		  
		store = new char[100];
		GetPrivateProfileString ("style",  "bgToolBarButtonColorChecked", "FFFFFF", store, 100 , FileName.toAscii().constData());	
		WritePrivateProfileString("style", "bgToolBarButtonColorChecked", store, FileName.toAscii().constData());
		styles.append(store);
		delete store;
	styles.append(
		  ";"
     "}"
);
	setStyleSheet(styles);	
	//QCoreApplication::
	//applicatin
	QString menuStyle(QString(
		""
	//	"font: bold 15px;"
		//"background-color: #ABABAB;"
		//"border: 2px solid black;"
		""
		"QMenu::item {"
	//	"font: bold 15px;"
		//"background-color: #ABABAB;"
		//"border: 2px solid black;"
		"}"
	
		));
	QMenuBar * mainMenu = new QMenuBar;
	imageViewer->menu1->setStyleSheet(menuStyle);
	imageViewer->menu2->setStyleSheet(menuStyle);
	imageViewer->menu3->setStyleSheet(menuStyle);
	imageViewer->menu4->setStyleSheet(menuStyle);
	//imageViewer->menu5->setStyleSheet(menuStyle);
	//imageViewer->menu6->setStyleSheet(menuStyle);
	
	//imageViewer->menu3->setTearOffEnabled(true);
	//imageViewer->menu4->setTearOffEnabled(true);
	//imageViewer->menu5->setTearOffEnabled(true);
	//imageViewer->menu6->setTearOffEnabled(true);
	//imageViewer->menu5->setParent(mainMenu);
	mainMenu->addMenu(imageViewer->menu1);
	mainMenu->addMenu(imageViewer->menu2);
	mainMenu->addMenu(imageViewer->menu3);
	mainMenu->addMenu(imageViewer->menu4);
	mainMenu->addMenu(imageViewer->menu5);
	mainMenu->addMenu(imageViewer->menu6);
	

	setMenuBar( mainMenu );	
	const TToolBarList &toolbarList = imageViewer->getToolBarList();
	for(unsigned int i = 0; i < toolbarList.size(); i++){
		addToolBar(toolbarList[i].area, toolbarList[i].tb);
	}
	FileName = Path + QString("\\windowPositions.ini");	
	file = CreateFile(FileName.toAscii().constData(), GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	result = GetFileSize (file, NULL);	
	CloseHandle(file);	
	store = new char[32000];
	GetPrivateProfileString ("state",  "state", "C:\\vidar.rus\\img", store, 32000 , FileName.toAscii().constData());	
	restoreState(QByteArray::fromBase64(QByteArray(store)));	
	QDesktopWidget desktopWidget;
	int numberOfMonitors = desktopWidget.numScreens();	
	int primaryScreen = desktopWidget.primaryScreen();	
	int secondScreen = primaryScreen;
	QRect rectPrimary = desktopWidget.screenGeometry(primaryScreen);
	QRect rect;
	QRect rectSecond;
	int isAutoDisplay = 0;
	int X = 0;
	int Y = 0;
	int W = 0;
	int H = 0;
	FileName = Path + QString("\\xray.INI");	
	Panel::StudyPath  = new char [256];
	strncpy_s (Panel::StudyPath, 2,  "", 2);	
	GetPrivateProfileString ("Setup",  "StudyPath", "C:\\vidar.rus\\img", Panel::StudyPath, 256 , FileName.toAscii().constData());		
	isAutoDisplay = GetPrivateProfileInt("Position",  "autoDisplay", 1, FileName.toAscii().constData());
	X = GetPrivateProfileInt("Position",  "X", 0, FileName.toAscii().constData());
	Y = GetPrivateProfileInt("Position",  "Y", 0, FileName.toAscii().constData());
	W = GetPrivateProfileInt("Position",  "W", 0, FileName.toAscii().constData());
	H = GetPrivateProfileInt("Position",  "H", 0, FileName.toAscii().constData());
	_itoa_s(isAutoDisplay, buff, 10);
	WritePrivateProfileStringA("Position", "autoDisplay", buff, FileName.toAscii().constData());
	if(desktopWidget.isVirtualDesktop() && isAutoDisplay == 1){
		//if(Panel::LOADFROMXRAYFOLDER){				
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() - 50, rectPrimary.top() - 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() + 50, rectPrimary.top() - 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
			}		
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() + rectPrimary.width() + 50, rectPrimary.top() - 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() + rectPrimary.width() + 50, rectPrimary.top() + 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() + rectPrimary.width() + 50, rectPrimary.top() + rectPrimary.height() + 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() + 50, rectPrimary.top() + rectPrimary.height() + 50);
				secondScreen = desktopWidget.screenNumber(point);
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() - 50, rectPrimary.top() + rectPrimary.height() + 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}
			if(primaryScreen == secondScreen || secondScreen == -1){
				QPoint point(rectPrimary.left() - 50, rectPrimary.top() + 50);
				secondScreen = desktopWidget.screenNumber(point);	
				rect = desktopWidget.availableGeometry (point);
				rectSecond = desktopWidget.screenGeometry(secondScreen);
			}	
		//}
	}
	if(isAutoDisplay == 1 || X + Y + W + H == 0){
		rectSecond = desktopWidget.screenGeometry(secondScreen);
		move(rectSecond.left(), rectSecond.top());	
		resize(rectSecond.width() - 7, rectSecond.height() - 50);
		showMaximized();		
	}else{		
		move(X, Y);	
		resize(W, H);
		show();		
	}	
	//showMinimized();
	showNormal();
	isWidgetShown = true;
	Loader loader;
	QStringList fileNames = loader.getListFiles(QString("images.txt")); 	
	if(fileNames.size() != 0){
		TLoadFilesDialog loadFilesDialog(fileNames);	
		loadFilesDialog.move(pos().x()  + width() / 2, pos().y() + height() / 2);
		loadFilesDialog.exec();	
	}
	//resetPanelStructure();
	return;
	TLoadFilesThread loadFilesThread;
	loadFilesThread.start();	
	while(!loadFilesThread.isRunning() || loadFilesThread.loadFiles == NULL){
		int a = 3;
	}	
	loadFilesThread.wait(100);
	QPushButton * button = new QPushButton("123", this->centralWidget());
	if(loadFilesThread.isRunning()){
	//	connect(loadFilesThread.loadFiles, 
	//		SIGNAL(signalLoaded(int, int, QString, unsigned int, unsigned int, unsigned int, unsigned int)), this, 
	//		SLOT( repaintWidget(int, int, QString, unsigned int, unsigned int , unsigned int, unsigned int)));
	//	connect(&loadFilesThread, SIGNAL(terminated()), this, SLOT(accept()));
	//	connect(&loadFilesThread, SIGNAL(finished ()), this, SLOT(accept()));
	//	connect( &cancel, SIGNAL(pressed()), this, SLOT(reject()) );
		loadFilesThread.loadFiles->setDirList(fileNames);
		loadFilesThread.loadFiles->setFilePath("");			
	}
	loadFilesThread.startParsing();
	while(loadFilesThread.isRunning()){
		int a  =1;
		QCoreApplication::processEvents();
	}
	int a = 3;
	
}

void VImageViewerMainWindow::closeEvent(QCloseEvent * event){	
	char buff[256];		
	QString Path = getWindowAppPath();	
	QString FileName = Path + QString("\\windowPositions.ini");		
	if(!QFile::exists(FileName)){
		QFile file(filePath);
		file.open(QIODevice::ReadOnly);
		file.close();
	}
	WritePrivateProfileString("state", "state", saveState().toBase64().data(), FileName.toAscii().constData());
	FileName = Path + QString("\\xray.INI");		
	_itoa_s(this->x(), buff, 10);
	char * X = buff;
	WritePrivateProfileString("Position", "X", X, FileName.toAscii().constData());
	_itoa_s(this->y(), buff, 10);
	char *  Y = buff;
	WritePrivateProfileString("Position", "Y", Y, FileName.toAscii().constData());	
	_itoa_s(this->width(), buff, 10);
	char *  W = buff;
	WritePrivateProfileString("Position", "W", W, FileName.toAscii().constData());
	_itoa_s(this->height(), buff, 10);		
	char *  H = buff;
	WritePrivateProfileString("Position", "H", H, FileName.toAscii().constData());	
	delete imageViewer;		
}
bool VImageViewerMainWindow::winEvent(MSG *message, long *result){	
	if( message->message == WM_COPYDATA ){	
		if(!isWidgetShown){
			HWND hwnd = FindWindowA((LPCSTR)NULL, "Vidar-XRAY");
			::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM) message->lParam);	
			return false;
		}
		//this->centralWidget()->drawText(100,100, "dfggggggggggggggggggggggggg");
		//QHBoxLayout * layout = new QHBoxLayout();
		//QLabel *label = new QLabel("waiting for saving..");
		//layout->addWidget(label);
		//this->topLevelWidget()->setLayout(layout);
		//label->show();		
		//label->repaint();
		//this->centralWidget()->repaint();			
		//RECT textRect;
		//textRect.bottom = 300;
		//textRect.right = 300;
		//textRect.top = 0;
		//textRect.left = 0;
		//::DrawText(this->centralWidget()->getDC(), "123", -1, &textRect, DT_SINGLELINE );
		//::DrawText(this->topLevelWidget()->getDC(), "123", -1, &textRect, DT_SINGLELINE );
		COPYDATASTRUCT* pCD = (COPYDATASTRUCT*) message->lParam;
		char buffer[1000];
		DIAGN_VidarMSG data;		
		strncpy_s(buffer, pCD->cbData - 1, (char *)pCD->lpData, pCD->cbData - 1); 	
		memcpy(&data, pCD->lpData, pCD->cbData);
		int  size  = 50000;		
		size = (unsigned char)data.Str1[0];
		memmove (data.Str1, data.Str1 + 1, size);
        data.Str1[size] = 0;
        size = (unsigned char)data.Str2[0];		
        memmove (data.Str2, data.Str2 + 1, size);
        data.Str2[size] = 0;
		//QMessageBox::warning(NULL, "WM_COPYDATA message",  data.Str1);	
		//QMessageBox::warning(this, "WM_COPYDATA message",  QString("%1").arg(data.Cmd ));		
		//if(imageViewer != NULL && isWidgetShown){
		//	showNormal();
		//	setFocus();
		//}
		if(data.Cmd == 5000){			
			showNormal();
		//	setFocus();
			ContainerPanel::clearStudies(0, false);	
			delete curFilter;
			curFilter = new QString(data.Str1);			
			QStringList dirs = getAllfilesFromSubDirs(Panel::StudyPath);		
			loadDicomFromPath(dirs, QString(data.Str2), QString(data.Str1));								
			ContainerPanel::SetAutoFillTopPanels();	
			QFile qFile;
			QString fileName(QCoreApplication::applicationDirPath() + QString("\\xrayLog.txt"));			
			qFile.setFileName(fileName); 	
			if (!qFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
				QMessageBox::warning(this, "WM_COPYDATA message",  "5000, cant write to file");				
			}		
			QTextStream out(&qFile);			
			out <<"5000 - "<< data.Str1 << "\\" << data.Str2 << "\\"<<QDateTime::currentDateTime().toString() <<"\\\n" ;			
			qFile.close();	
			//if(is)
			//QCoreApplication::processEvents();
			/*if(dirs.size() != 0 && !firstLoading){
				showMinimized();
				showMaximized();
				setFocus();
				showNormal();
			}*/		
			firstLoading = false;
		}		
		if(data.Cmd == 5001) {
			ContainerPanel::clearStudies(0, false);
			Panel::deleteAllDICOMStruct(data.Str1);			
			ContainerPanel::SetAutoFillTopPanels();				
			QFile qFile;
			QString fileName(QCoreApplication::applicationDirPath() + QString("\\xrayLog.txt"));		
			qFile.setFileName(fileName); 	
			if (!qFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
				QMessageBox::warning(this, "WM_COPYDATA message",  "5001, cant write to file");			
			}			
			QTextStream out(&qFile);			
			out <<"5001 - "<< data.Str1 << "\\" << data.Str2 << "\\"<<QDateTime::currentDateTime().toString() <<"\\\n" ;
			qFile.close();			
			if(imageViewer != NULL && isWidgetShown)
				showMinimized();
		}
		if(data.Cmd == 5002) {		
			showNormal();
			ContainerPanel::clearStudies(0, false);
			Panel::deleteAllDICOMStruct();			
			QStringList newFiles;
			QStringList dirs = getAllfilesFromSubDirs(Panel::StudyPath);		
			loadDicomFromPath(dirs, QString(data.Str2), QString(data.Str1));				
			ContainerPanel::SetAutoFillTopPanels();		
			QFile  qFile;
			QString fileName(QCoreApplication::applicationDirPath() + QString("\\xrayLog.txt"));		
			qFile.setFileName(fileName); 	

			if (!qFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
				QMessageBox::warning(this, "WM_COPYDATA message",  "5002, cant write to file");				
			}						
			QTextStream out(&qFile);			
			out <<"5002 - "<< data.Str1 << "\\" << data.Str2 << "\\"<<QDateTime::currentDateTime().toString() <<"\\\n" ;
			qFile.close();								firstLoading = false;
	
		}
		//data.Cmd = 5003;
		if(data.Cmd == 5003) {
			showNormal();
			//setFocus();	
			char buff[256];						
			QString Path = getWindowAppPath();	
			QString FileName = Path + QString("\\settings.ini");		
			if(!QFile::exists(FileName)){
				QFile file(filePath);
				file.open(QIODevice::ReadOnly);
				file.close();
			}			
			char * wadoQueryString = new char[256];
			char * vidarQueryString = new char[256];		
			QString * urlStr = new QString(data.Str2);
			GetPrivateProfileString ("serverSettings",  "wadoQueryString", "?requestType=WADO&objectUID=", wadoQueryString, 256 , FileName.toAscii().constData());	
			GetPrivateProfileString ("serverSettings",  "vidarQueryString", "?requestType=WADO&studyUID=",vidarQueryString, 256 , FileName.toAscii().constData());	
			WritePrivateProfileString("serverSettings", "wadoQueryString", wadoQueryString, FileName.toAscii().constData());
			WritePrivateProfileString("serverSettings", "vidarQueryString", vidarQueryString, FileName.toAscii().constData());				
			char * URLString = new char[1024];				
			urlStr->trimmed();
			if(urlStr->size() == 0){
				GetPrivateProfileString ("ServerSettings",  "URL", "http://ivan:8080/vidar-web/wado.htm", URLString, 256 , FileName.toAscii().constData());	
				urlStr = new QString(URLString);
			}
			QUrl url(* urlStr);
			//QUrl url ("http://vidar03:8084/vidar-web/wado.htm");
			WritePrivateProfileString("ServerSettings", "URL", urlStr->toAscii().constData(), FileName.toAscii().constData());
			QList<QPair<QString, QString> > arglist;
			arglist.append( QPair<QString, QString>( "requestType", "WADO"));
			arglist.append( QPair<QString, QString>( "studyUID", data.Str1));	
			//arglist.append( QPair<QString, QString>( "studyUID", "1.2.840.113619.2.22.288.4576.9776.20090728.203209"));	
			

			url.setQueryItems(arglist);		
			FileName = Path + QString("\\xray.ini");		
			if(!QFile::exists(FileName.toAscii().constData())){
				QFile file(filePath);
				file.open(QIODevice::ReadOnly);
				file.close();
			}				
			char * programName = new char [1024];
			BOOLEAN isRomanDownloader = GetPrivateProfileInt("downloadSettings",  "isRomanDownloader", 0, FileName.toAscii().constData());
			_itoa_s(isRomanDownloader, buff, 10);
			WritePrivateProfileStringA("downloadSettings", "isRomanDownloader", buff, FileName.toAscii().constData());
			
			GetPrivateProfileString ("downloadSettings",  "programName", "DownloadManagerC.exe", programName, 256 , FileName.toAscii().constData());
			WritePrivateProfileStringA("downloadSettings", "programName", programName, FileName.toAscii().constData());

			int numberThreads = GetPrivateProfileInt("downloadSettings",  "numberThreads", 4, FileName.toAscii().constData());
			if(numberThreads <=0)
				numberThreads = 4;
			if(numberThreads > 50)
				numberThreads = 50;
			_itoa_s(numberThreads, buff, 10);
			WritePrivateProfileStringA("downloadSettings", "numberThreads", buff, FileName.toAscii().constData());		
			if(isRomanDownloader){				
				getFromRomanManager(getVrefFileFromURL(url).toAscii().constData(), programName ,numberThreads, *curFilter);
			}else{				
				QDir dir(QString(QCoreApplication::applicationDirPath()).append("/saveImage"));	
				removeFolder(dir);	
				QStringList list = dir.entryList( QDir::AllEntries | QDir::NoDotAndDotDot );
				for(int j = 0; j < list.size(); j++){
					QString fileName = list[j];				
					QFile qFile(fileName);
					qFile.remove(QCoreApplication::applicationDirPath() + QString("/saveImage/") + fileName);
				}	
				dir.mkdir (QCoreApplication::applicationDirPath() + QString("\\saveImage"));
				TDownloadFilesDialog downloadFilesDialog (url, *curFilter, true);
				connect(&downloadFilesDialog, 
					SIGNAL(signalDownload(int, int, int, int, bool)), this, 
					SLOT( downloading(int, int, int , int, bool)));
				while(!downloadFilesDialog.downloadFilesMultiThread.isTerminateAll()){
					QCoreApplication::processEvents();
				}
				label->hide();
				disconnect(&downloadFilesDialog, 
					SIGNAL(signalDownload(int, int, int, int, bool)), this, 
					SLOT( downloading(int, int, int , int, bool)));
			}			
			QStringList fileNames;
			fileNames << QCoreApplication::applicationDirPath() + QString("\\saveImage");	
			/*
			TLoadFilesDialog loadFilesDialog(fileNames, *curFilter);
			loadFilesDialog.move(pos().x()  + width() / 2, pos().y() + height() / 2);
			loadFilesDialog.exec();
			*/

			TLoadFilesThread loadFilesThread;
			loadFilesThread.start();	
			while(!loadFilesThread.isRunning() || loadFilesThread.loadFiles == NULL){
				int a = 3;
			}	
			loadFilesThread.wait(100);			
			if(loadFilesThread.isRunning()){
					connect(loadFilesThread.loadFiles, 
						SIGNAL(signalLoaded(int, int, QString, unsigned int, unsigned int, unsigned int, unsigned int)), this, 
						SLOT( loading(int, int, QString, unsigned int, unsigned int , unsigned int, unsigned int)));			
				loadFilesThread.loadFiles->setDirList(fileNames, *curFilter);
				loadFilesThread.loadFiles->setFilePath("");			
			}
			loadFilesThread.startParsing();
			while(loadFilesThread.isRunning()){
				int a = 1;
				QCoreApplication::processEvents();
			}
			label->hide();
			disconnect(loadFilesThread.loadFiles, 
				SIGNAL(signalLoaded(int, int, QString, unsigned int, unsigned int, unsigned int, unsigned int)), this, 
				SLOT( loading(int, int, QString, unsigned int, unsigned int , unsigned int, unsigned int)));			

			delete programName;						
			ContainerPanel::setFirstTopPanel(*curFilter);
			ContainerPanel::SetAutoFillTopPanels();					
			firstLoading = false;
			QFile qFile;
			QString fileName(QCoreApplication::applicationDirPath() + QString("\\xrayLog.txt"));				
			qFile.setFileName(fileName); 	
			if (!qFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)){
				QMessageBox::warning(this, "WM_COPYDATA message",  "5003, cant write to file");

			}		
			QTextStream out(&qFile);			
			out <<"5003 - "<< data.Str1 << "\\" << data.Str2 << "\\"<<QDateTime::currentDateTime().toString() <<"\\\n" ;
			out <<"host - "<< url.host() << "\\ port - " << url.port() << "\\ wadoQueryString - "<< wadoQueryString
				<< "\\ vidarQueryString - "<< vidarQueryString <<QDateTime::currentDateTime().toString() <<"\\\n" ;
			qFile.close();				
		}		
		if(data.Cmd == 50) {			
			close();
		}
		
		if(data.Cmd == 5004) {			
			char  buff[10];
			QString Path = getWindowAppPath();				
			QString FileName = Path + QString("\\xray.INI");
			BOOLEAN isRomanDownloader = GetPrivateProfileInt("downloadSettings",  "isRomanDownloader", 0, FileName.toAscii().constData());
			_itoa_s(isRomanDownloader, buff, 10);
			WritePrivateProfileStringA("downloadSettings", "isRomanDownloader", buff , FileName.toAscii().constData());
			int numberThreads = GetPrivateProfileInt("downloadSettings",  "numberThreads", 2, FileName.toAscii().constData());
			if(numberThreads <=0)
				numberThreads = 3;
			if(numberThreads > 50)
				numberThreads = 50;
			_itoa_s(numberThreads, buff, 10);
			WritePrivateProfileStringA("downloadSettings", "numberThreads", buff, FileName.toAscii().constData());
			char * programName = new char [1024];
			GetPrivateProfileString ("downloadSettings",  "programName", "DownloadManagerC.exe", programName, 256 , FileName.toAscii().constData());
			WritePrivateProfileStringA("downloadSettings", "programName", programName, FileName.toAscii().constData());	
			if(isRomanDownloader){			
				getFromRomanManager(data.Str1, programName, numberThreads);			
			}
			else{
				onTRYDOWNLOADFILESFASTFromFileVREF(data.Str1);				
			}

			QStringList fileNames;
			fileNames << QCoreApplication::applicationDirPath() + QString("\\saveImage");	
			TLoadFilesDialog loadFilesDialog(fileNames, *curFilter);
			loadFilesDialog.move(pos().x()  + width() / 2, pos().y() + height() / 2);
			loadFilesDialog.exec();
			delete programName;						
			ContainerPanel::setFirstTopPanel(*curFilter);			
			firstLoading = false;

		}		
	}	
	return false;
}

void VImageViewerMainWindow::onTRYDOWNLOADFILESFAST(QStringList files){
	imageViewer->onTRYDOWNLOADFILESFAST(files);
}

void VImageViewerMainWindow::onTRYDOWNLOADFILESFASTFromFileVREF(QString fileName){
	imageViewer->onTRYDOWNLOADFILESFASTFromFileVREF(fileName);
}
/*void VImageViewerMainWindow::onTRYADDFILESFAST(QStringList files){
	imageViewer->onTRYADDFILESFAST(files);
}*/
VImageViewerMainWindow::~VImageViewerMainWindow(){
	delete Panel::mEMManager;
}

void VImageViewerMainWindow::mouseMoveEvent( QMouseEvent * event )
{
	int x = event->globalX();
	int y = event->globalY();
}


void VImageViewerMainWindow::loading( int curNumberOfFile, int numberOfAllFiles, QString curFileName, unsigned int currentByte, unsigned int total, unsigned int currentByteAll, unsigned int totalAll){
	if(label == NULL)
		label = new QLabel(" ", this->topLevelWidget());	
	label->show();	
	label->move(this->topLevelWidget()->width() / 3, this->topLevelWidget()->height() - 100);
	label->setMinimumWidth(this->topLevelWidget()->width() / 2);

	label->setText(QString("  Loaded file: ") + curFileName +
		QString("  ") + QString("%1/%2").arg(curNumberOfFile).arg(numberOfAllFiles));			
}


void VImageViewerMainWindow::downloading( int time, int numberFile, int size, int done, bool isSavingFilesToDisk )
{
	if(label == NULL)
		label = new QLabel("123", this->topLevelWidget());	
	label->show();	
	label->move(this->topLevelWidget()->width() / 3, this->topLevelWidget()->height() - 100);
	label->setMinimumWidth(this->topLevelWidget()->width() / 2);

	label->setText((tr("  file: %1/%2;size: %3 kB; time: %4 seconds")
		.arg(numberFile)
		.arg(size)
		.arg(done)
		.arg(time)));
}